import api from '@/api';
import defaultSettings from '@/config/defaultSettings';
import { downByBlob, downByUrl } from '@/utils/file/downFile';
import { getFileTypeWithExt } from '@/utils/file/file';
import { message } from 'ant-design-vue/es';
import { FileItem } from '@/types';
// const Base64 = require('js-base64').Base64;
import { Base64 } from 'js-base64';
import { getCurrentInstance } from 'vue';
export const useDownFile = () => {
    const instance: any = getCurrentInstance();
    // 下载所有文件模板
    const downTemplate = async (type: string) => {
        const query = {
            type
        };
        const fileNameObj = {
            productinsidereview: '产品内部评审表.doc',
            onlineaduit: '上线审核表.doc',
            testreport: '自测报告.doc',
            requiredelivery: '需求交付说明书.doc',
            requiredoc_purchase: '需求文档（外采产品）.doc',
            requiredoc_randd: '需求文档（自研产品）.doc',
            productplancompose: '产品计划排期模板.docx',
            character_tree: '特性树导入模板.xlsx'
        };
        const res = await api.fileModel.downTemplate(query, {
            responseType: 'blob'
        });
        res && downByBlob(res, fileNameObj[type]);
    };
    // 下载创建需求时的模板
    const downRequireTemplate = async (type: number) => {
        const query = {
            type
        };
        const res = await api.fileModel.downRequireTemplate(query, {
            responseType: 'blob'
        });
        res && downByBlob(res, type === 1 ? '产品需求参考模版.xlsx' : '业务需求参考模版.xlsx');
    };
    // 根据wpsurl下载文件
    const downFileByUrlWps = async (urlWps: string, fileName: string) => {
        const query = {
            url: urlWps,
            type: '1'
        };
        const { success, moule, errorMsg } = await api.fileModel.downloadWpsFile(query);
        if (success) {
            downByUrl(fileName, moule);
        } else {
            message.error(errorMsg);
        }
    };
    // 下载文件
    const downFile = async (item: FileItem, isAutoTest: boolean) => {
        if (!item.url && !item.urlWps) {return}
        // 判断是否有后缀，wpsurl无后缀
        if (item.url.includes('.')) {
            const { production, otherPlatformUrl } = defaultSettings;
            // 调用acmdb下载逻辑
            if (item.connectType === '测试报告' && isAutoTest) {
                let url = Base64.encode(item.url);
                url = Base64.encode(url);
                if (item.fileName) {
                    const query = `?filename=${url}&type=''`;
                    const { protocol, hostname } = document.location;
                    const port = otherPlatformUrl['acmdb'].port;
                    const link = production ? `${protocol}//${hostname}:${port}` : otherPlatformUrl['acmdb'].devTargetUrl;
                    downByUrl(item.fileName, `${link}/api/activiti/activitiFile/${query}`);
                }
            }
            // 自身平台逻辑
            else {
                // const query = `?url=${item.url}`;
                // const { protocol, hostname, port } = document.location;
                // const link = production ? `${protocol}//${hostname}:${port}` : 'http://10.141.42.21:20018';
                // downByUrl(item.fileName, `${link}/api/file/down/${query}`);

                const res = await api.fileModel.down({
                    url: item.url
                }, {
                    responseType: 'blob'
                });
                res && downByBlob(res, item.fileName);
            }
        } else {
            downFileByUrlWps(item.url, item.fileName);
        }
    };
    // 预览
    const previewFile = async (item: FileItem, isAutoTest = false) => {
        if (!item.url && !item.urlWps) {return}
        const type = getFileTypeWithExt(item.fileName);
        //wps文件
        if (item.connectType === '测试报告' && isAutoTest) {
            const formData = new FormData();
            formData.append('url', item.url);
            formData.append('type', 'version');
            formData.append('operation', 'read');
            const { moule, success } = await api.acmdbModel.previewByWPS(formData);
            if (success) {
                window.open(moule);
            } else {
                message.error('文件不存在');
            }
        }
        else if (item.connectType === '更新包') {
            message.error('该文件暂不支持预览功能');
        } else {
            if (['word', 'pdf', 'excel', 'ppt'].includes(type)) {
                const query = {
                    id: item.id,
                    url: item.url
                    // urlWps: item.urlWps
                };
                const { success, moule } = await api.fileModel.preview(query);
                if (success) {
                    window.open(moule);
                } else {
                    message.error('文件不存在');
                }
            }
            //图片文件
            else if (type === 'image') {
                const d = await api.fileModel.down({
                    url: item.url
                }, {
                    responseType: 'blob'
                });
                const url = URL.createObjectURL(d);
                instance.proxy.$mitt.emit('previewImg', url);
            } else {
                message.error('该文件暂不支持预览功能');
            }
        }

    };
    return {
        downTemplate,
        downRequireTemplate,
        downFile,
        previewFile
    };
};